package com.apes.fn.mdm.offer.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.mdm.offer.model.OfferGroup;
import com.apes.fn.mdm.offer.repository.OfferGroupRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OfferGroupService extends DomainService {

    @Autowired
    private OfferGroupRepository offerGroupRepository;

    /**
     * 查询所有数据
     * @param request
     * @return
     */
    public Page<OfferGroup> conditionQuery(SimpleRequest request){
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.ASC, "name");
        return offerGroupRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }

    /**
     * 报价组新增 修改
     * @param request
     * @return
     */
    public OfferGroup save(SimpleRequest request){
        JSONObject jo = request.getJO();
        OfferGroup offerGroup = new OfferGroup();
        offerGroup.setId(jo.getString("id"));
        offerGroup.setVersion(jo.getInteger("version")==null?0:jo.getInteger("version"));
        offerGroup.setName(jo.getString("name"));
        User personnelName = getBean(UserRepository.class).findByName(jo.getJSONObject("personnelName").getString("name"));
        offerGroup.setPersonnelName(personnelName);
        try {
          return   offerGroupRepository.saveAndFlush(offerGroup);
        }catch (Exception e){
            throw new RuntimeException("报价组或名字已存在！");
        }
    }


    /**
     * 报价组删除
     * @param request
     * @return
     */
    public void delete(SimpleRequest request){
        OfferGroup offerGroup = request.getO(OfferGroup.class);
        offerGroupRepository.delete(offerGroup);
    }


    /**
     * 根据门店报价组查询报价组信息
     * @param request
     * @return
     */
    public List<OfferGroup> findByDeptName(SimpleRequest request){
        List<String> nameList = new ArrayList<>();
        nameList.add(request.getJO().getString("name"));
        List<OfferGroup> offerGroups = offerGroupRepository.findByNameIn(nameList);
        return offerGroups;
    }


}
